package com.impress.adapter;

import java.io.File;
import java.util.List;

import android.content.Context;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.impress.ItemWebView;
import com.impress.R;
import com.impress.Utility;
import com.impress.adapter.BriefItemsAdapter.ViewHolder;
import com.impress.listener.OnScrollListener;
import com.impress.model.Item;
import com.impress.service.HtmlHandler;
import com.impress.service.ItemService;

public class DetailItemsAdapter extends BaseItemsListAdapter {

	private ItemService mItemService;
	private OnScrollListener mScrollListener;
	public DetailItemsAdapter(Context context, List<Item> items,OnScrollListener scrollListener) {
		super(context, items);
		mItemService = new ItemService(context);
		this.mScrollListener = scrollListener;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Item item = mItems.get(position);
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(mContext).inflate(R.layout.item_content, null);
			holder.webView = (WebView)convertView.findViewById(R.id.item_web);
			holder.layout = (LinearLayout)convertView.findViewById(R.id.item_content_linearlayout);
			convertView.setTag(holder);
		}else {
			holder = (ViewHolder)convertView.getTag();
		}		
		File itemFile = mItemService.getItemDownloadFile(item);
		holder.webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		holder.webView.getSettings().setJavaScriptEnabled(true);
		holder.webView.setScrollbarFadingEnabled(true);
		holder.webView.setHorizontalScrollBarEnabled(false);
		holder.webView.setFocusableInTouchMode(true);
		holder.webView.requestFocusFromTouch();
//		holder.webView.setOnTouchListener(onTouchListener);
		if(itemFile!=null){
			holder.webView.loadUrl("file://"+itemFile.getAbsolutePath());
		}else{
			holder.webView.loadDataWithBaseURL(null, 
					HtmlHandler.generateHTML(item.getContent(), item), "text/html", "utf-8", null);
//			holder.webView.loadUrl(item.getAlternateUrl());
		}
//		holder.webView.loadUrl("http://jiepang.com/m/help");
		if(holder.webView instanceof ItemWebView){
			((ItemWebView)(holder.webView)).setOnScrollListener(mScrollListener);
		}
		return convertView;
	}
	
	class ViewHolder{
		WebView webView;
		LinearLayout layout;
	}

}
